package com.cloudeye.logtest.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Created by lafangyuan on 2020/12/30.
 */
@Slf4j
public class HeartbeatClient {

    private String host = "localhost";
    private int port = 8888;

    private int readerTimeSeconds = 0;
    private int writeTimeSeconds = 5;


    public void connect(Bootstrap bootstrap,EventLoopGroup workerGroup) {
        try {
            bootstrap.group(workerGroup); // (2)
            bootstrap.channel(NioSocketChannel.class); // (3)
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new IdleStateHandler(readerTimeSeconds,writeTimeSeconds,0, TimeUnit.SECONDS),
                            new StringEncoder(),
                            new ConnectClientHandler(HeartbeatClient.this));
                }
            });

            // Start the client.
            ChannelFuture f = bootstrap.connect(host, port)
                    .addListener((ChannelFuture futureLisntener)->{
                        EventLoop eventLoop = futureLisntener.channel().eventLoop();
                        if(!futureLisntener.isSuccess()){
                            log.warn("服务器连接失败，重新尝试...");
                            futureLisntener.channel().eventLoop()
                                    .schedule(()->connect(new Bootstrap(),eventLoop),5,TimeUnit.SECONDS);
                        }
                    })
                    .sync(); // (5)


            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new HeartbeatClient().connect(new Bootstrap(),new NioEventLoopGroup());
    }
}
